﻿using AppData;
using Microsoft.AspNetCore.Mvc;
using System;
using ServerShared;
using AppData.DTO;
using System.Security.Policy;
using System.Xml.Linq;
using Google.Protobuf.WellKnownTypes;
using MySqlX.XDevAPI.Relational;
using Microsoft.AspNetCore.Components.Web;
using System.Text;
using static Org.BouncyCastle.Crypto.Engines.SM2Engine;

namespace AppServer.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class MoviesController : ControllerBase
    {
        readonly IImageHandler _imageHandler;
        //private readonly IWebHostEnvironment _webHostEnvironment;

        public MoviesController(IImageHandler imageHandler)
        {
            _imageHandler = imageHandler;
            //_webHostEnvironment = webHostEnvironment;
            //GameDebug.Log("MoviesController init:" /*+ webHostEnvironment.WebRootPath*/);

        }

        [HttpGet("get_recommended_movies")]
        public ActionResult<string> get_recommended_movies(string movieType, int num)
        //public IEnumerable<Book> get_recommended_videos(int num)
        {
            GameDebug.Log($"get_recommended_movies type:{movieType}, num:{num}");

            System.Enum.TryParse(movieType, out MovieGenre type);

            List<ShortMovie> videos = new List<ShortMovie>();
            videos.AddRange(TableHelper.GetAllMovies(type, num));//videosSaver.GetAllvideos(enumValue);
            List<MovieItemData> retItems = videos.Map(e => new MovieItemData(e)).ToList();
            TypeMovieItems ret = new TypeMovieItems()
            {
                itemDatas = retItems,
            };
            return Newtonsoft.Json.JsonConvert.SerializeObject(ret);
        }

        [HttpGet( "get_movies_with_name")]
        public ActionResult<string> get_movies_with_name(string name)
            //public IEnumerable<Book> get_recommended_videos(int num)
        {
            GameDebug.Log($"get_movies_with_name：{name}");

            int num = 1000;

            List<ShortMovie> videos = new List<ShortMovie>();
            for (int i = (int)SqlTable.movies_A; i <= (int)SqlTable.movies_Z; i++)
            {
                var genrevideos = TableHelper.GetMoviesWithName((SqlTable)i,name, num);//videosSaver.GetAllvideos(enumValue);

                foreach (var book in genrevideos)
                {
                    videos.Add(book);

                    if (videos.Count >= num)
                    {
                        return Newtonsoft.Json.JsonConvert.SerializeObject(videos);
                    }
                }
            }
            List<MovieItemData> retItems = videos.Map(e => new MovieItemData(e)).ToList();
            TypeMovieItems ret = new TypeMovieItems()
            {
                itemDatas = retItems,
            };
            return Newtonsoft.Json.JsonConvert.SerializeObject(ret);
        }

        [HttpGet("check_movie_name_exist")]
        public ActionResult<string> check_movie_name_exist(string movieName)
        {
            GameDebug.Log($"check_movie_name_exist movieName:{movieName}");

            bool exist = TableHelper.FindInMovieTable(movieName) != null;

            Dictionary<string, bool> dict = new Dictionary<string, bool>() { { "exist", exist } };

            return Newtonsoft.Json.JsonConvert.SerializeObject(dict);
        }

        /// <summary>
        /// 创建短剧合集
        /// </summary>
        /// <param name="maintainData"></param>
        /// <returns></returns>
        [HttpPost("create_movie")]
        public ActionResult<string> create_movie(MovieProto movie)
        {
            GameDebug.Log($"创建Movie合集：{movie?.name} {movie?.author} ");

            if (movie == null || string.IsNullOrEmpty(movie.name))
            {
                GameDebug.LogError($"短剧名字不能为空");
                return BadRequest();
            }

            byte[] fileBytes;
            if (movie.file == null)
            {
                GameDebug.Log("封面文件为空");
                return BadRequest();
            }
            using (var ms = new MemoryStream())
            {
                movie.file.CopyTo(ms);
                fileBytes = ms.ToArray();
            }
            if (fileBytes == null || fileBytes.Length <= 0)
            {
                GameDebug.Log("封面文件为空");
                return BadRequest();
            }

            string genre = movies.GetMovieGenre(movie.name);

            var table = movies.AddMovie(movie.name, 0, movie.sub_genre, movie.description,
                movie.author, movie.uploader, movie.publishDate);

            TextureSaver.SaveVideoTexture(table.id, genre, fileBytes);

            ShortMovie shortMovie = TableHelper.Table2Movie(table);
            var responseData = new MovieData(shortMovie);
            return Newtonsoft.Json.JsonConvert.SerializeObject(responseData);
        }

        //public class MovieCoverProto
        //{
        //    public long movieId { get; set; }
        //    public string movieName { get; set; }
        //    public IFormFile file{get;set;}
        //}

        //[HttpPost("upload_movie_cover")]
        //public async Task<ActionResult<string>> upload_movie_cover(MovieCoverProto proto)
        //{
        //    long movieId = proto.movieId; string movieName = proto.movieName; IFormFile file = proto.file;
        //    GameDebug.Log($"upload_movie_cover movieId:{movieId}  FileName:{file.FileName}");

        //    byte[] fileBytes;
        //    using (var ms = new MemoryStream())
        //    {
        //        file.CopyTo(ms);
        //        fileBytes = ms.ToArray();
        //    }
        //    if (fileBytes == null || fileBytes.Length <= 0)
        //    {
        //        GameDebug.Log("文件为空");
        //        return BadRequest();
        //    }

        //    var ret = await _imageHandler.UploadImage(file);
        //    GameDebug.Log($"upload cover result:{(ret as ObjectResult)?.Value}");
            
        //    var exist = TableHelper.FindInMovieTable(movieId, movieName);
        //    if (exist == null)
        //    {
        //        GameDebug.LogError($"短剧不存在 movieId:{movieId}  movieName:{movieName}");
        //        return BadRequest();
        //    }

        //    string genre = movies.GetMovieGenre(movieName);
        //    TextureSaver.SaveVideoTexture(movieId, genre, fileBytes);
            
        //    ShortMovie bookRet = TableHelper.Table2Movie(exist);
        //    var responseData = new MovieItemData(bookRet);
        //    return Newtonsoft.Json.JsonConvert.SerializeObject(responseData);
        //}
        /// <summary>
        /// 上传video
        /// </summary>
        /// <param name="maintainData"></param>
        /// <returns></returns>
        [HttpPost("upload_video")]
        public ActionResult<string> upload_video(VideoProto video)
        {
            GameDebug.Log($"上传video：{video?.movieId}, {video?.episodeId} ");

            if (video == null || string.IsNullOrEmpty(video.movieName))
            {
                GameDebug.LogError($"短剧名字不能为空");
                return BadRequest();
            }

            string genre = movies.GetMovieGenre(video.movieName);

            long movieId = video.movieId;

            var table = TableHelper.FindInMovieTable(movieId, video.movieName);

            if(table == null)
            {
                GameDebug.LogError($"找不到短剧合集：{video.movieName}  movieId:{movieId}");
                return BadRequest();
            }

            byte[] fileBytes;
            if (video.file == null)
            {
                GameDebug.Log("视频文件为空");
                return BadRequest();
            }
            using (var ms = new MemoryStream())
            {
                video.file.CopyTo(ms);
                fileBytes = ms.ToArray();
            }
            if (fileBytes == null || fileBytes.Length <= 0)
            {
                GameDebug.Log("视频文件为空");
                return BadRequest();
            }

            var videosTable = videos.AddVideo(movieId, video.episodeId, video.episodeName,
                video.episodeName, CommonFunctions.getDateTime(), true);//TODO approved

            table.episode_count = table.episode_count < video.episodeId ? video.episodeId : table.episode_count;

            int row = movies.UpdateEpisodeCount(table.id, table.name, table.episode_count);
            GameDebug.Log($"修改了{row}行，episode_count：{table.episode_count}");
            int ret = VideosSaver.SaveVideo(genre, movieId, video.episodeId, fileBytes);

            if (ret < 0)
            {
                GameDebug.LogError($"保存文件失败：{movieId} ");
                return BadRequest();
            }

            ShortMovie shortMovie = TableHelper.Table2Movie(table);
            var responseData = new MovieData(shortMovie);
            return Newtonsoft.Json.JsonConvert.SerializeObject(responseData);
        }

        [HttpGet("get_movie")]
        public ActionResult<string> GetMovie(string movieName)
        {
            string genre = movies.GetMovieGenre(movieName);

            var table = TableHelper.FindInMovieTable(movieName);

            ShortMovie shortMovie = TableHelper.Table2Movie(table);
            var responseData = new MovieData(shortMovie);
            return Newtonsoft.Json.JsonConvert.SerializeObject(responseData);
        }

        [HttpGet("get_image")]
        public IActionResult GetImage(string relativePath)
        {
            string imagePath = Path.Combine(ServerConfig.filesDataRoot, relativePath);

            if (System.IO.File.Exists(imagePath))
            {
                byte[] imageBytes = System.IO.File.ReadAllBytes(imagePath);
                return File(imageBytes, "image/jpeg"); // 可根据实际图片类型设置Content-Type
            }
            GameDebug.Log($"cant find img at path:{imagePath}");
            return NotFound();
        }
        [HttpGet("get_video")]
        public IActionResult GetVideo(string relativePath)
        {
            string path = Path.Combine(ServerConfig.filesDataRoot, relativePath);

            if (System.IO.File.Exists(path))
            {
                byte[] imageBytes = System.IO.File.ReadAllBytes(path);
                return File(imageBytes, "video/mp4"); // 可根据实际图片类型设置Content-Type
            }

            GameDebug.Log($"cant find video at path:{path}");
            return NotFound();
        }
    }
}
